package com.apes.fn.misc.contract;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.soe.store.database.repository.BusinessAttributeValueRepository;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import com.apes.pi.service.PiManager;
import com.apes.project.jekunAuto.timeTask.BaseService;
import com.apes.scm.account.account.repository.CooperationRepository;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.contract.repository.ContractRepository;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @ClassName ContractSynService
 * @Description TODO
 * @Author zyc
 * @Date 2020/1/9 11:21
 * @Version 1.0
 **/
@Service("contractSynService")
public class ContractSynService extends BaseService {
    @Autowired
    PiManager piManager;
    @Autowired
    ContractRepository contractRepository;
    @Autowired
    EnumerationRepository enumerationRepository;

    public static final String CONTRACTSYNSERVICE_CONTRACT_TYPE = "Contract.contractType.supplier";
    public static final String CONTRACTSYNSERVICE_CONTRACT_TYPE_PLATFORM = "Contract.contractType.platform";

    /**
     * 查询老系统合同数据
     *
     * @param request
     * @return
     */
    public JSONArray synContract(SimpleRequest request) {
        JSONArray objects = piManager.timedTaskSynErp("ipmServicePlanService.qryContract");
        return objects;
    }

    public Map saveContract(SimpleRequest simpleRequest) {
        JSONObject jo = simpleRequest.getJO();
        Contract contract = Tools.map(jo, Contract.class);
        Contract result = contractRepository.findOne(contract.getId());
        if (result != null) {
            contract = result;
        }

        contract.setSystemSource(jo.getString("systemSource") == null ? null : jo.getString("systemSource"));

        //设置公司等信息
        try {
            contract.setCompany(SpringManager.getBean(PartyRoleRepository.class).findOne(jo.getString("GSID")));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //设置采购部门等信息
        try {
            contract.setDept(SpringManager.getBean(DeptRepository.class).
                    findAll(JpaDsl.toCriteriaByEq("deptType.type.id", "businessClass", "deptType.id", "000006", "company.id", jo.getString("GSID")))
                    .stream().findFirst().get());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //设置供应商等信息  通过对照表找供应商对应的party
        try {
            contract.setPartner(
                    SpringManager.getBean(ContrastPartyCodeRepository.class).findAll(JpaDsl.toCriteriaByEq("gysid", jo.getString("GYSID")))
                            .stream().findFirst().get().getParty().getPartyRoles().stream().filter((partyRole) -> {
                        return "Supplier".equals(partyRole.getRole().getId());
                    }).findFirst().get()
            );
        } catch (Exception e) {
            throw new RuntimeException("未找到供应商");
        }

//        try {
//            if ("1007".equals(jo.getString("CGZZID"))) {
//                contract.setContractType(SpringManager.getBean(BusinessAttributeValueRepository.class).findOne(CONTRACTSYNSERVICE_CONTRACT_TYPE_PLATFORM));
//            } else {
//                contract.setContractType(SpringManager.getBean(BusinessAttributeValueRepository.class).findOne(CONTRACTSYNSERVICE_CONTRACT_TYPE));
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }

        try {
            if ("2".equals(jo.getString("CGHTLX"))) {
                contract.setContractType(SpringManager.getBean(BusinessAttributeValueRepository.class).findOne(CONTRACTSYNSERVICE_CONTRACT_TYPE_PLATFORM));
            }else {
                contract.setContractType(SpringManager.getBean(BusinessAttributeValueRepository.class).findOne(CONTRACTSYNSERVICE_CONTRACT_TYPE));
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }

        try {
            String settlementType = "";
            if ("month".equalsIgnoreCase(jo.getString("JSZQ"))) {
                settlementType = "month";
            } else if ("halfMonth".equalsIgnoreCase(jo.getString("JSZQ"))) {
                settlementType = "halfMonth";
            } else if ("week".equalsIgnoreCase(jo.getString("JSZQ"))) {
                settlementType = "week";
            } else if ("bill".equalsIgnoreCase(jo.getString("JSZQ"))) {
                settlementType = "bill";
            } else if ("totalCash".equalsIgnoreCase(jo.getString("JSZQ"))){
                settlementType = "totalCash";
            } else if ("deptCash".equalsIgnoreCase(jo.getString("JSZQ"))){
                settlementType = "deptCash";
            } else {
                // 存在采购瞎给数据的情况，老胡批准默认为账单
                settlementType = "bill";
            }
            contract.setSettlementType(enumerationRepository.findAll(JpaDsl.toCriteriaByEq("code", settlementType, "type.id", "settlementType")).stream().findFirst().get());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        try {
            String coopration = "";
            if (jo.getInteger("COOPERATION") == 0) {
                coopration = "distribution";
            } else if (jo.getInteger("COOPERATION") == 1) {
                coopration = "consignment";
            } else if (jo.getInteger("COOPERATION") == 2) {
                coopration = "consignment";
                contract.setConsignInstall(true);
            } else if (jo.getInteger("COOPERATION") == 3) {
                coopration = "distribution";
                contract.setConsignInstall(true);
            }else{
                throw new RuntimeException("合作方式不允许为空，请维护老框架合作方式");
            }
            contract.setCooperation(SpringManager.getBean(CooperationRepository.class).findOne(coopration));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        try {
            String JHFSID = "";
            if ("CONTRACT.CARRYTYPE.SELFMENTION".equals(jo.getString("JHFSID"))) {
                JHFSID = "Contract.carryType.selfMention";
            } else if ("CONTRACT.CARRYTYPE.DELIVERY".equals(jo.getString("JHFSID"))) {
                JHFSID = "Contract.carryType.delivery";
            }else{
                JHFSID = "Contract.carryType.selfMention";
            }
            //contract.setCarryType(SpringManager.getBean(BusinessAttributeValueRepository.class).findOne(JHFSID));
            contract.setCarryType(enumerationRepository.findAll(JpaDsl.toCriteriaByEq("code", JHFSID, "type.id", "carryType")).stream().findFirst().get());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //当合同来自老框架的时候，给外部合同编号赋值
        if (jo.getString("systemSource") != null && "0".equals(jo.getString("systemSource"))) {
            contract.setOriginId(jo.getString("CGHTH"));
        }

        contract.setState("approve");
        contract.setMoveType(SpringManager.getBean(EnumerationRepository.class).findOne("one"));   // 交货方式
        return MapUtil.mapped(contract);
    }


    public Contract save(SimpleRequest request) throws Exception {
        Contract contract = request.getO(Contract.class);
        return contractRepository.saveAndFlush(contract);
    }

}

